package br.edu.ufcg.splab.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;


import br.edu.ufcg.splab.core.InterfaceEdge;
import br.edu.ufcg.splab.core.InterfaceGraph;
import br.edu.ufcg.splab.core.InterfaceVertex;

public class WriterToTGF {
	private static final String END_OF_LINE = System.getProperty("line.separator");
	
	
	/**
	 * Method responsible for creating the file based on the {@link https://sites.google.com/a/computacao.ufcg.edu.br/lts-bt/inputs tgf}
	 *  format,to be possible generate the design of graph.
	 * 
	 * @param graph
	 * 			Graph to be generate the file
	 * @param file
	 * 			File to be written			
	 * @return
	 * 		The file with the informations of a graph
	 * @throws IOException
	 * 		Throws IOException if an error occurs in the writing process.
	 */
	public File getTGFfromGraph(InterfaceGraph graph,File file) throws IOException{
		StringBuffer sb = new StringBuffer();
		Collection<InterfaceVertex> vertices = graph.getStates().values();
		
		sb.append(graph.getRoot().getLabel()+" "+graph.getRoot().getLabel());
		sb.append(END_OF_LINE);
		
		for(InterfaceVertex vertex : vertices){
		//to prevent add again the root
			if(vertex.getLabel() != graph.getRoot().getLabel()){
				sb.append(vertex.getLabel()+" "+vertex.getLabel());	
				sb.append(END_OF_LINE);
			}
		}
		
		sb.append("#"+ END_OF_LINE);
		
		for(InterfaceEdge edge : graph.getEdges()){
			sb.append(edge.getFrom().getLabel()+" "+edge.getTo().getLabel());
			sb.append(" " + edge.getLabel());
			sb.append(END_OF_LINE);				
		}	
		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
		bw.write(sb.toString());
		bw.close();
		return file;	
	}

	}
	
	
	

